package com.gitee.ywj1352.pservlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 使用 JNDI 来查找
 *
 * @author: yangwenjie.a
 * @date: 2021/7/5 18:01
 * @description:
 */
public class PDemoServlet extends HttpServlet {

    private ApplicationContext applicationContext = ApplicationContext.getInstance();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建
        DataSource dataSource = applicationContext.getEnvBean(DataSource.class, "jdbc/geekbang");
        StringBuilder sb = new StringBuilder();
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(
                "SELECT Table_schema,table_name,create_time FROM information_schema.`TABLES` LIMIT 1;");
            ResultSet resultSet = preparedStatement.executeQuery();
            sb.append("从information_schema.`TABLES`中取出一条数据: </br>");
            while (resultSet.next()) {
                sb.append("  Table_schema =").append(resultSet.getString("Table_schema")).append("</br>");
                sb.append("  table_name =").append(resultSet.getString("table_name")).append("</br>");
                sb.append("  create_time =").append(resultSet.getString("create_time")).append("</br>");
            }
            resultSet.close();
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        req.setAttribute("table", sb.toString());

        req.getRequestDispatcher("/Hello.jsp").forward(req, resp);
    }

}
